﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.Helper;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.Helper;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace RabbitDownload.WebSite.Pixiv.ClearData
{
    internal class ClearWithLst
    {
        /// <summary>
        /// 处理黑名单文件的路径
        /// </summary>
        public static string PixivBanIdPath = StaticValue.TempPath + "PixivBanId.txt";

        /// <summary>
        /// P站通过鉴别的列表
        /// </summary>
        public static string PixivAdoptIdPath = StaticValue.TempPath + "PixivDAdoptId.txt";

        /// <summary>
        /// 读取的黑名单缓存
        /// </summary>
        public static List<string> PixivBanIdList = FileHelper.ReadAllLine(PixivBanIdPath);

        /// <summary>
        /// 读取已通过词库
        /// </summary>
        public static List<string> PixivAdoptList = FileHelper.ReadAllLine(PixivAdoptIdPath);

        /// <summary>
        /// 处理单个列表文件
        /// </summary>
        /// <param name="LstFloderPath"></param>
        /// <param name="ExcludeKeyFile"></param>
        public void HandleLstFloder(string LstFloderPath, string ExcludeKeyFile, CWebclient cWebclient)
        {
            List<string> FoloderList = Directory.GetFiles(LstFloderPath, "*.*",
                      SearchOption.TopDirectoryOnly).Where(s => s.EndsWith(".lst") || s.EndsWith(".txt")).ToList();
            List<string> ExcludeList = FileHelper.ReadAllLine(ExcludeKeyFile);
            foreach (string line in FoloderList)
            {
                Console.WriteLine(line);
                HandleLst(line, ExcludeList, cWebclient);
            }
        }

        /// <summary>
        /// 处理单个列表文件
        /// </summary>
        /// <param name="LstFilePath"></param>
        /// <param name="ExcludeKeyFile"></param>
        public void HandleLst(string LstFilePath, string ExcludeKeyFile, CWebclient cWebclient)
        {
            HandleLst(LstFilePath, FileHelper.ReadAllLine(ExcludeKeyFile), cWebclient);
        }

        /// <summary>
        /// 处理单个文件的情况
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="ExcludeKeyList"></param>
        public void HandleLst(string FilePath, List<string> ExcludeKeyList, CWebclient cWebclient)
        {
            if (FilePath == "")
                return;
            List<string> ImgList = FileHelper.ReadAllLine(FilePath);
            List<string> TempImgList = new List<string>();
            foreach (String Line in ImgList)
            {
                if (Line == "")
                    continue;

                if (GetImgJumpFlag(Line, ExcludeKeyList, cWebclient))
                    continue;
                TempImgList.Add(Line);
            }
            if (TempImgList.Count > 0)
                FileHelper.WriteList(FileNameHelper.CreateFileNameWithChildFloder(FilePath, "_已处理"), TempImgList);
            else
                Console.WriteLine("全部未通过，不写入资源。");
        }

        /// <summary>
        /// 获取图片是否触发跳出，触发返回true
        /// </summary>
        /// <param name="PixivLink"></param>
        /// <returns></returns>
        private bool GetImgJumpFlag(string PixivLink, List<string> ExcludeKeyList, CWebclient cWebclient)
        {
            string PixivId = TextHelper.RegexText(PixivLink, "/[0-9]{1,}_p");
            PixivId = TextHelper.ReplaceTextEnhance(PixivId, "(/|_p)", "");
            if (ReadOldLogJump(PixivId, PixivBanIdList) || PixivId == "")
            {
                Console.WriteLine("缓存：{0}需要屏蔽，跳出。", PixivId);
                return true;
            }
            if (ReadOldLogJump(PixivId, PixivAdoptList))
            {
                Console.WriteLine("缓存：{0}通过校验，跳出。", PixivId);
                return false;
            }
            string API = "https://www.pixiv.net/ajax/user/1039353/illusts?ids[0]=" + PixivId;
            /*
            WebHeaderCollection webHeaderCollection = WebHelper.PcWebHeader();
            webHeaderCollection.Add("Cookie:PHPSESSID=24587510_656bbb6e15136786f1bfeddfd03043a4; p_ab_id=4; p_ab_id_2=5; device_token=6d750eb0d979c20914dc5c850a4b4596; privacy_policy_agreement=1; c_type=22; a_type=0; b_type=1; d_type=1; module_orders_mypage=%5B%7B%22name%22%3A%22sketch_live%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22tag_follow%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22recommended_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22showcase%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22everyone_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22following_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22mypixiv_new_illusts%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22fanbox%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22featured_tags%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22contests%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22user_events%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22sensei_courses%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22spotlight%22%2C%22visible%22%3Atrue%7D%2C%7B%22name%22%3A%22booth_follow_items%22%2C%22visible%22%3Atrue%7D%5D; yuid=KJECMnI37; login_ever=yes; tag_view_ranking=RTJMXD26Ak~_hSAdpN9rx~BU9SQkS-zU~Lt-oEicbBr~y8GNntYHsi~UX647z2Emo~WcTW9TCOx9~w-HSw8XliK~q9iT9w2e89~ETjPkL0e6r~kjfJ5uXq4m~j2lJ8_51Vq~2fTx4fs8a8~XMeKnjoeVa~zlLh7B6pY8~OXID0M1Z5f~8jLEb-nz4N~2mHMFxA0cV~xZ6jtQjaj9~Ac_mADAVwx~4gzX-RNalt~BtXd1-LPRH~lxfrUKMf9f~Ie2c51_4Sp~pusqGCt8hY~k3L7pRbDNW~NpsIVvS-GF~q3eUobDMJW~QR9TTbOVZg~RcahSSzeRf~t4pUmgSzLU~fAloiTkhNQ~KBvqQAOz1L~CVM9sX8pPs~CjhwUq-Zyv~uM2AGxB6mo~D8iC6PNkf4~KvAGITxIxH~Wi3c6_nhTn~nRp2ZLPLbj~ik8EzwIZs-~YHDnWmOB_1~zIv0cf5VVk~L4gUvD2V2D~wm1AQSuCHO~wtOVRQvcYm~RHvdZoY1rz~UeoqiV3Iea~zyKU3Q5L4C~PTyxATIsK0~CMH7y9clRf~A7nC3xKpED~ibKqKQj_16~1HSjrqSB3U~D8cfQCDYAl~jH0uD88V6F~xysHqsBBcv~pvU1D1orJa~u0RWz3pVej~IYKskIYUSo~d2Bh-L3fof~aFExPdJFeZ~z12DrMDD3j~p-LHfJBhfK~RRFW9UEFcZ~VkSVCrWwii~IeHKec7IaX~aC55Umcfh1~-uc-JwIkBl~T2awT-K8wj~SS4or2NSx-~CvzNxNMpiE~Qa8ggRsDmW~J99Gky7rC1~bYfigtcm_W~RFxnRuAN7K~j6p5JJYkX8~ghYEfzZ0Ex~qx-Tlvmbdj~foWAd9-whs~V8D3XaY0dQ~Tsg8fUvGRQ~JwWYItCgHw~O9MCeYZD50~tvr1QK3tEf~O8uNAHjPrw~PDYR8fAeWf~gDabresXoX~FO9eywXQPJ~Un9jtLFTha~3ox2ohmUmA~YXRn5Mr377~psKw48NVys~TBAh5YDdLW~wvG5Sk7fMM~rGJ6scy9ti~pkIbRQnIKo~-VFw3PY9jA~drtdHheU9Q~gKn-GQJBYN; is_sensei_service_user=1");
            String Shtml = WebHelper.HttpPcGet(API, webHeaderCollection);*/
            String Shtml = cWebclient.GetHtml(API, WebHelper.PcWebHeader());
            Shtml = TextHelper.RegexText(Shtml, "\"tags\":\\[.*?\\]")

                + TextHelper.RegexText(Shtml, ",\"userId\":\"[0-9]{0,}\"");

            try
            {
                if (Shtml == "")
                    return true;
                Shtml = "{" + Shtml + "}";
                Console.WriteLine(Shtml);
                PixivArtInfo pixivArtInfo = JsonConvert.DeserializeObject<PixivArtInfo>(Shtml);
                pixivArtInfo.tags.Add(pixivArtInfo.userId);
                bool ExitFlag = ListHelper.CompareRepetition(pixivArtInfo.tags, ExcludeKeyList);

                if (!ExitFlag)
                {
                    Console.WriteLine("验证通过");
                    FileHelper.AppendText(PixivAdoptIdPath, PixivId);
                    PixivAdoptList.Add(PixivId);
                    return false;
                }
                FileHelper.AppendText(PixivBanIdPath, PixivId);
                PixivBanIdList.Add(PixivId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("初始化JSON失败");
                PrintLog.Log(ex.Message);
            }
            return true;
        }

        /// <summary>
        /// 判断是否在黑名单列表中
        /// </summary>
        /// <param name="PixivId"></param>
        /// <returns></returns>
        private bool ReadOldLogJump(string PixivId, List<string> JudgeList)
        {
            return JudgeList.Contains(PixivId);
        }

        public class PixivArtInfo
        {
            /// <summary>
            ///标签列表
            /// </summary>
            public List<string> tags { get; set; }

            /// <summary>
            /// 用户ID
            /// </summary>
            public string userId { get; set; }
        }
    }
}